<template>
	<view class="content">
		<view class="upload-area">
			<uni-file-picker
				v-model="fileList"
				file-mediatype="all"
				@select="handleFileChange"
				limit="1"
				file-extname="pdf"
				:auto-upload="false"
				:disabled="!!file"
				@success="handleUploadSuccess"
				@fail="handleUploadFail"
				@delete="handleDelete"
			>
				<template v-slot:default>
					<button type="primary" :disabled="!!file">
						{{ file ? '文件已选择' : '导入简历pdf文件' }}
					</button>
				</template>
			</uni-file-picker>
		</view>
		<uni-forms
			ref="form"
			:model="formData"
			:rules="rules"
			style="width: 100%"
			labelWidth="80px"
		>
			<uni-forms-item required label="姓名" name="fullName" class="full-width">
				<uni-easyinput v-model="formData.fullName" placeholder="姓名" />
			</uni-forms-item>
			<uni-forms-item
				required
				label="籍贯"
				name="nativePlace"
				class="full-width"
			>
				<uni-easyinput v-model="formData.nativePlace" placeholder="籍贯" />
			</uni-forms-item>
			<uni-forms-item required label="性别" name="gender" class="full-width">
				<uni-easyinput v-model="formData.gender" placeholder="性别" />
			</uni-forms-item>
			<uni-forms-item
				required
				label="本科院校"
				name="undergraduateSchool"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.undergraduateSchool"
					placeholder="本科院校"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="本科专业"
				name="undergraduateMajor"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.undergraduateMajor"
					placeholder="本科专业"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="学习时间"
				name="undergraduateTimeRange"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.undergraduateTimeRange"
					placeholder="本科学习时间"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="硕士院校"
				name="masterSchool"
				class="full-width"
			>
				<uni-easyinput v-model="formData.masterSchool" placeholder="硕士院校" />
			</uni-forms-item>
			<uni-forms-item
				required
				label="硕士专业"
				name="masterMajor"
				class="full-width"
			>
				<uni-easyinput v-model="formData.masterMajor" placeholder="硕士专业" />
			</uni-forms-item>
			<uni-forms-item
				required
				label="学习时间"
				name="masterTimeRange"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.masterTimeRange"
					placeholder="硕士学习时间"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="博士院校"
				name="doctorSchool"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.doctorSchool"
					placeholder="博士院校(没有填“无”)"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="博士专业"
				name="doctorMajor"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.doctorMajor"
					placeholder="博士专业(没有填“无”)"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="学习时间"
				name="doctorTimeRange"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.doctorTimeRange"
					placeholder="博士学习时间(没有填“无”)"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="电话号码"
				name="phoneNumber"
				class="full-width"
			>
				<uni-easyinput v-model="formData.phoneNumber" placeholder="电话号码" />
			</uni-forms-item>
			<uni-forms-item
				required
				label="导师姓名"
				name="supervisorName"
				class="full-width"
			>
				<uni-easyinput
					v-model="formData.supervisorName"
					placeholder="导师姓名"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="实习经历"
				name="internshipExperience"
				class="full-width"
			>
				<uni-easyinput
					type="textarea"
					v-model="formData.internshipExperience"
					placeholder="实习经历"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="研究领域"
				name="researchField"
				class="full-width"
			>
				<uni-easyinput
					type="textarea"
					v-model="formData.researchField"
					placeholder="研究领域"
				/>
			</uni-forms-item>
			<uni-forms-item
				required
				label="论文题目"
				name="thesisTitle"
				class="full-width"
			>
				<uni-easyinput
					type="textarea"
					v-model="formData.thesisTitle"
					placeholder="论文题目"
				/>
			</uni-forms-item>
			<uni-forms-item
				label="相关证书（仅支持图片文件）"
				name="attachments"
				class="full-width"
			>
				<uni-file-picker
					v-model="attachments"
					file-mediatype="image"
					mode="grid"
					limit="9"
					file-extname="bmp,gif,jpeg,png,jpg"
					:auto-upload="false"
					@select="handleAttachmentsChange"
					@success="handleAttachmentsUploadSuccess"
					@fail="handleAttachmentsUploadFail"
				>
				</uni-file-picker>
			</uni-forms-item>
			<button
				form-type="submit"
				type="primary"
				@click="confirmSubmit"
				class="full-width"
			>
				提交简历
			</button>
		</uni-forms>
	</view>
</template>

<script>
import config from '@/config';
import { setUserInfo } from '@/api/system/user.js';
export default {
	data() {
		return {
			fileList: [],
			file: null,
			attachments: [],
			attachmentsTemp: [],
			allowedExtensions: ['bmp', 'gif', 'jpg', 'jpeg', 'png'], // 允许的文件后缀
			formData: {
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				remark: null,
				id: null,
				fullName: '',
				nativePlace: '',
				gender: '',
				undergraduateSchool: '',
				undergraduateMajor: '',
				undergraduateTimeRange: '',
				masterSchool: '',
				masterMajor: '',
				masterTimeRange: '',
				doctorSchool: '无',
				doctorMajor: '无',
				doctorTimeRange: '无',
				phoneNumber: '',
				supervisorName: '',
				internshipExperience: '',
				researchField: '',
				thesisTitle: '',
				hireCandidateAttachList: null,
				resumesPath: '',
			},
			rules: {
				fullName: { rules: [{ required: true, errorMessage: '姓名不能为空' }] },
				nativePlace: {
					rules: [{ required: true, errorMessage: '籍贯不能为空' }],
				},
				gender: { rules: [{ required: true, errorMessage: '性别不能为空' }] },
				undergraduateSchool: {
					rules: [{ required: true, errorMessage: '本科院校不能为空' }],
				},
				undergraduateMajor: {
					rules: [{ required: true, errorMessage: '本科专业不能为空' }],
				},
				undergraduateTimeRange: {
					rules: [{ required: true, errorMessage: '本科学习时间不能为空' }],
				},
				masterSchool: {
					rules: [{ required: true, errorMessage: '硕士院校不能为空' }],
				},
				masterMajor: {
					rules: [{ required: true, errorMessage: '硕士专业不能为空' }],
				},
				masterTimeRange: {
					rules: [{ required: true, errorMessage: '硕士学习时间不能为空' }],
				},
				doctorSchool: {
					rules: [{ required: true, errorMessage: '博士院校不能为空' }],
				},
				doctorMajor: {
					rules: [{ required: true, errorMessage: '博士专业不能为空' }],
				},
				doctorTimeRange: {
					rules: [{ required: true, errorMessage: '博士学习时间不能为空' }],
				},
				phoneNumber: {
					rules: [{ required: true, errorMessage: '电话号码不能为空' }],
				},
				supervisorName: {
					rules: [{ required: true, errorMessage: '导师姓名不能为空' }],
				},
				internshipExperience: {
					rules: [{ required: true, errorMessage: '实习经历不能为空' }],
				},
				researchField: {
					rules: [{ required: true, errorMessage: '研究领域不能为空' }],
				},
				thesisTitle: {
					rules: [{ required: true, errorMessage: '论文题目不能为空' }],
				},
			},
		};
	},
	methods: {
		handleFileChange(event) {
			const file = event.tempFiles[0].file;
			if (file.type !== 'application/pdf') {
				uni.showToast({ title: '请选择一个PDF文件', icon: 'none' });
				this.file = null;
				return;
			}
			this.file = file;
			console.log(this.file);
			this.uploadFile();
		},
		handleDelete() {
			this.file = null;
		},
		async uploadFile() {
			if (!this.file) {
				uni.showToast({ title: '请选择一个文件', icon: 'none' });
				return;
			}
			uni.showLoading({ title: '上传中...', mask: true });
			const formData = new FormData();
			formData.append('file', this.file);

			try {
				const response = await fetch(
					config.baseUrl + '/system/candidate/openapi/extract',
					{
						method: 'POST',
						body: formData,
					}
				);
				uni.hideLoading();
				if (response.ok) {
					const data = await response.json();
					if (data.code === 200) {
						this.fillFormData(data.data);
						uni.showToast({ title: '上传成功', icon: 'success' });
					} else {
						uni.showToast({ title: '上传失败', icon: 'none' });
					}
				} else {
					uni.showToast({ title: '上传失败', icon: 'none' });
				}
			} catch (error) {
				uni.hideLoading();
				console.error('上传错误:', error);
				uni.showToast({ title: '上传错误', icon: 'none' });
			}
		},
		handleAttachmentsChange(event) {
			this.attachmentsTemp = event.tempFiles.map((file) => file.file);
			console.log(this.attachmentsTemp);

			// 校验文件后缀
			const invalidFiles = this.attachmentsTemp.filter((file) => {
				const extension = file.name.split('.').pop().toLowerCase();
				return !this.allowedExtensions.includes(extension);
			});
			if (invalidFiles.length > 0) {
				uni.showToast({
					title: '请选择有效的文件类型 (BMP, GIF, JPG, JPEG, PNG)',
					icon: 'none',
				});
				return;
			}

			this.uploadAttachments();
		},
		async uploadAttachments() {
			if (this.attachmentsTemp.length === 0) {
				uni.showToast({ title: '请选择附件', icon: 'none' });
				return;
			}

			const formData = new FormData();
			this.attachmentsTemp.forEach((file, index) => {
				formData.append(`files`, file);
			});

			try {
				const response = await fetch(
					config.baseUrl + '/system/candidate/openapi/uploads',
					{
						method: 'POST',
						body: formData,
					}
				);
				console.log(response);

				if (response.ok) {
					const data = await response.json();
					console.log(data);
					if (data.code === 200) {
						const urls = data.urls.split(',');
						const fileNames = data.fileNames.split(',');
						const fileSizes = data.fileSizes.split(',');
						const originalFilenames = data.originalFilenames.split(',');

						const attachList = urls.map((url, index) => ({
							attachName: originalFilenames[index],
							attachUrl: url,
							attachSize: parseInt(fileSizes[index], 10),
							attachType: 2,
						}));

						// 更新 attachments 数组为上传后的图片 URL 对象
						this.attachments = [
							...this.attachments,
							...attachList.map((attach) => ({
								url: attach.attachUrl,
								name: attach.attachName,
								extname: attach.attachName.split('.').pop(),
							})),
						];
						console.log('uoloadSuccess===', this.attachments);

						// 更新 hireCandidateAttachList
						this.formData.hireCandidateAttachList = [
							...(this.formData.hireCandidateAttachList || []),
							...attachList,
						];
						uni.showToast({ title: '附件上传成功', icon: 'success' });
					} else {
						console.log('uoloadError===', this.attachments);
						// this.attachments.pop()
						uni.showToast({ title: '附件上传失败', icon: 'none' });
					}
				} else {
					uni.showToast({ title: '附件上传失败', icon: 'none' });
				}
			} catch (error) {
				console.error('附件上传错误:', error);
				uni.showToast({ title: '附件上传错误', icon: 'none' });
			}
		},
		handleUploadSuccess(event) {
			console.log('上传成功:', event);
		},
		handleUploadFail(event) {
			console.log('上传失败:', event);
		},
		handleAttachmentsUploadSuccess(event) {
			console.log('附件上传成功:', event);
		},
		handleAttachmentsUploadFail(event) {
			console.log('附件上传失败:', event);
		},
		fillFormData(data) {
			if (!data.doctorSchool) {
				data.doctorSchool = '无';
			}
			if (!data.doctorMajor) {
				data.doctorMajor = '无';
			}
			if (!data.doctorTimeRange) {
				data.doctorTimeRange = '无';
			}
			if (data.internshipExperience) {
				data.internshipExperience = data.internshipExperience.replace(
					/,/g,
					'\n'
				);
			}
			this.formData = { ...this.formData, ...data };
		},
		confirmSubmit() {
			uni.showModal({
				title: '友情提醒',
				content: '简历只有一次提交机会，请谨慎填写！检查无误后点击确认提交！',
				success: (res) => {
					if (res.confirm) {
						this.submitForm();
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				},
			});
		},
		submitForm() {
			this.$refs.form
				.validate()
				.then((res) => {
					console.log('表单数据:', this.formData);
					uni.showLoading({ title: '提交中...', mask: true });
					setUserInfo(this.formData)
						.then((res) => {
							// uni.showToast({ title: '提交成功', icon: 'success' });
							uni.hideLoading();
							uni.showModal({
								title: '恭喜',
								content: '您的简历已提交成功！期待您的加入！',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										this.$store
											.dispatch('LogOut')
											.then(() => {
												uni.redirectTo({
													url: '/pages/login',
												});
											})
											.finally(() => {
												// this.$tab.reLaunch('/pages/index');
											});
									} else if (res.cancel) {
										this.$store
											.dispatch('LogOut')
											.then(() => {
												uni.redirectTo({
													url: '/pages/login',
												});
											})
											.finally(() => {
												// this.$tab.reLaunch('/pages/index');
											});
									}
								},
							});

							// setTimeout(() => {
							// 	this.$store
							// 		.dispatch('LogOut')
							// 		.then(() => {
							// 			uni.redirectTo({
							// 				url: '/pages/login',
							// 			});
							// 		})
							// 		.finally(() => {
							// 			// this.$tab.reLaunch('/pages/index');
							// 		});
							// }, 1000);
						})
						.catch((err) => {
              // console.log(err);
              
							// uni.showToast({ title: err.msg, icon: 'error' });
							uni.hideLoading();
						});
				})
				.catch((err) => {
					console.log('表单验证失败:', err);
					uni.showToast({ title: '表单验证失败', icon: 'none' });
				});
		},
		resetForm() {
			this.$refs.form.resetFields();
		},
	},
};
</script>

<style scoped>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20px;
	background-color: #fff;
}

.upload-area,
.attachments-area {
	margin-bottom: 20px;
}

button {
	margin-top: 20px;
}

/* 确保每个表单项占满整个宽度 */
.full-width {
	width: 100%;
}

/* 确保表单项内容占满整个宽度 */
.full-width .uni-forms-item__content {
	width: 100%;
}

/* 确保输入框占满整个宽度 */
.full-width .uni-easyinput {
	width: 100%;
}

/* 确保文件选择器占满整个宽度 */
.full-width .uni-file-picker {
	width: 100%;
}
</style>
